package com.ruoyi.project.mobile.jiaqin;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.jiaqin.company.domain.Company;
import com.ruoyi.project.jiaqin.company.service.ICompanyService;
import com.ruoyi.project.jiaqin.followmember.domain.JiaqinFollowMember;
import com.ruoyi.project.jiaqin.followmember.service.IJiaqinFollowMemberService;
import com.ruoyi.project.jiaqin.numbertips.domain.NumberTips;
import com.ruoyi.project.jiaqin.numbertips.service.INumberTipsService;
import com.ruoyi.project.jiaqin.quoted.domain.QuotedPrice;
import com.ruoyi.project.jiaqin.quoted.service.IQuotedPriceService;
import com.ruoyi.project.jiaqin.region.domain.Region;
import com.ruoyi.project.jiaqin.region.service.IRegionService;
import com.ruoyi.project.jiaqin.reportquote.domain.ReportQuote;
import com.ruoyi.project.jiaqin.reportquote.service.IReportQuoteService;
import com.ruoyi.project.jiaqin.reportsupply.domain.ReportSupply;
import com.ruoyi.project.jiaqin.reportsupply.service.IReportSupplyService;
import com.ruoyi.project.jiaqin.supply.domain.Supply;
import com.ruoyi.project.jiaqin.supply.service.ISupplyService;
import com.ruoyi.project.jiaqin.supplyclass.domain.SupplyClass;
import com.ruoyi.project.jiaqin.supplyclass.service.ISupplyClassService;
import com.ruoyi.project.jiaqin.supplyclasskey.domain.SupplyClassAttrKey;
import com.ruoyi.project.jiaqin.supplyclasskey.service.ISupplyClassAttrKeyService;
import com.ruoyi.project.jiaqin.supplyimg.domain.SupplyImg;
import com.ruoyi.project.jiaqin.supplyimg.service.ISupplyImgService;
import com.ruoyi.project.jiaqin.wanttobuy.domain.WantToBuy;
import com.ruoyi.project.jiaqin.wanttobuy.service.IWantToBuyService;
import com.ruoyi.project.jiaqin.wanttobuycollect.domain.WantToBuyCollect;
import com.ruoyi.project.jiaqin.wanttobuycollect.service.IWantToBuyCollectService;
import com.ruoyi.project.mobile.ApiNewController;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.messageuser.domain.MessageUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/jq/supply")
public class ApiSupplyController extends BaseController {

    @Autowired
    private IQuotedPriceService iQuotedPriceService;

    @Autowired
    private IWantToBuyService iWantToBuyService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private ISupplyService iSupplyService;

    @Autowired
    private IReportSupplyService iReportSupplyService;

    @Autowired
    private IReportQuoteService iReportQuoteService;

    @Autowired
    private ISupplyClassService iSupplyClassService;

    @Autowired
    private ISupplyClassAttrKeyService iSupplyClassAttrKeyService;
    @Autowired
    private IRegionService regionService;

    /**
     * 供需: 获取一级分类列表
     * @return
     */
    @GetMapping("/getSupplyClassOne")
    public R getSupplyClassOne(){
        HashMap<String, Object> map = new HashMap<>();
        SupplyClass supplyClass = new SupplyClass();
        supplyClass.setLevel(0);
        List<SupplyClass> list = iSupplyClassService.selectSupplyClassList(supplyClass);
        map.put("data",list);
        return R.ok(map);
    }

    /**
     * 供需: 获取二级或三级分类列表
     * @return
     */
    @GetMapping("/getSupplyClassByParentId")
    public R getSupplyClassByParentId(String parentId){
        HashMap<String, Object> map = new HashMap<>();
        SupplyClass supplyClass = new SupplyClass();
        supplyClass.setParentId(parentId);
        List<SupplyClass> list = iSupplyClassService.selectSupplyClassList(supplyClass);
        map.put("data",list);
        return R.ok(map);
    }

    /**
     *
     *
     *
     * @return
     */
    @GetMapping("/getClassAttrs")
    public R getClassAttrs(String supplyClassId){
        HashMap<String, Object> map = new HashMap<>();
        SupplyClassAttrKey classAttrKey = new SupplyClassAttrKey();
        classAttrKey.setSupplyClassId(supplyClassId);
        List<SupplyClassAttrKey> list = iSupplyClassAttrKeyService.selectSupplyClassAttrKeyList(classAttrKey);
        map.put("data",list);
        return R.ok(map);
    }
    /**
     * 发布求购
     * @param wantToBuy
     * @return
     */
    @PostMapping("/releaseWantToBuy")
    public R releaseWantToBuy(@RequestBody WantToBuy wantToBuy){
        if(wantToBuy.getMemberId() == null || wantToBuy.getMemberId().equals("")){
            return R.error("发布求购失败");
        }
        Member member = memberService.selectMemberById(wantToBuy.getMemberId());
        if (member.getIsVip() == 0 && member.getIsJqVip() == 0) {
            return R.error("您不是会员，请先注册会员");
        }
        if (member.getStatus() == 1) {
            return R.error("您的账户因违规使用而被冻结，详情请联系我们平台");
        }
        // 添加我的求购、关注求购数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(wantToBuy.getMemberId());

        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setWantToBuyNum(1);
            numberTipsService.updateNumberTips(tips);
        }
        JiaqinFollowMember followMember = new JiaqinFollowMember();
        followMember.setFollowMemberId(wantToBuy.getMemberId());
        List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
        if (followMemberList.size() > 0) {
            for (JiaqinFollowMember JFM : followMemberList) {
                JFM.setId(JFM.getId());
                JFM.setWantToBuyNum(1);
                jiaqinFollowMemberService.updateJiaqinFollowMember(JFM);
                NumberTips byMemberId = numberTipsService.selectNumberTipsByMemberId(JFM.getMemberId());
                if (byMemberId != null) {
                    NumberTips tips1 = new NumberTips();
                    tips1.setId(byMemberId.getId());
                    tips1.setFollowWantToBuyNum(1);
                    numberTipsService.updateNumberTips(tips1);
                }
            }
        }
        wantToBuy.setStatus(0);//设置状态采购中
        wantToBuy.setViews(0L);//设置浏览量
        wantToBuy.setReleaseTime(new Date());//设置发布时间

        Region provinceName = regionService.selectRegionById(wantToBuy.getProvince());
        wantToBuy.setProvinceName(provinceName.getName());//省名
        Region cityName = regionService.selectRegionById(wantToBuy.getCity());
        wantToBuy.setCityName(cityName.getName());//市名
        Region areaName = regionService.selectRegionById(wantToBuy.getArea());
        wantToBuy.setAreaName(areaName.getName());//区名
        return iWantToBuyService.insertWantToBuy(wantToBuy)>0?R.ok():R.error("发布失败");
    }

    @Autowired
    private IWantToBuyCollectService wantToBuyCollectService;
    @Autowired
    private ICompanyService companyService;
    /**
     * 根据ID获取采购详情
     * @param wantToBuy
     * @return
     */
    @GetMapping("/getWantToBuyById")
    public R getWantToBuyById(String wantToBuyId, String memberId){
        HashMap<String, Object> map = new HashMap<>();
        WantToBuy wantToBuy = iWantToBuyService.selectWantToBuyById(wantToBuyId);
//        Long numSeeCache = redisTemplate.opsForValue().increment(wantToBuy.getId(),1);
        wantToBuy.setId(wantToBuyId);
        wantToBuy.setViews(wantToBuy.getViews()+1); // 浏览量+1
        iWantToBuyService.updateWantToBuy(wantToBuy);
        SupplyClass supplyClass = iSupplyClassService.selectSupplyClassById(wantToBuy.getThrClassId());
        if (supplyClass != null) {
            wantToBuy.setThrClassName(supplyClass.getName());
        }
        // 是否是企业
        Member memberById = memberService.selectMemberById(wantToBuy.getMemberId());
        if (memberById != null) {
            Company company = companyService.selectCompanyByMemberId(memberById.getId());
            // 个人距离
            if (company != null) {
                wantToBuy.setIsCompany(1);// 企业
                wantToBuy.setMemberCompanyId(company.getId());// 企业ID
                wantToBuy.setHeadpic(company.getCompanyAvatar());// 企业头像
                wantToBuy.setMemberName(memberById.getUsername());// 企业姓名
                wantToBuy.setCompanyName(company.getCompanyName());// 公司名
                wantToBuy.setPhone(company.getCompanyPhone());// 企业电话
            } else {
                wantToBuy.setIsCompany(0);// 个人
                wantToBuy.setMemberCompanyId(memberById.getId());// 个人ID
                wantToBuy.setHeadpic(memberById.getHeadpic());// 个人头像
                wantToBuy.setMemberName(memberById.getUsername());// 个人姓名
                wantToBuy.setCompanyName(memberById.getCorporation());// 公司名
                wantToBuy.setPhone(memberById.getMobile());// 个人电话
            }
            wantToBuy.setDistance( Integer.toString((int) (Math.random() * 900 + 100)));// 企业距离
        }
        // 是否收藏
        WantToBuyCollect wantToBuyCollect = new WantToBuyCollect();
        wantToBuyCollect.setMemberId(memberId);
        wantToBuyCollect.setWantToBuyId(wantToBuyId);
        List<WantToBuyCollect> buyCollects = wantToBuyCollectService.selectWantToBuyCollectList(wantToBuyCollect);
        if (buyCollects.size() > 0) {
            wantToBuy.setIsCollect(1);
        } else {
            wantToBuy.setIsCollect(0);
        }
        map.put("data",wantToBuy);
        return R.ok(map);
    }

    /**
     * 根据采购ID下架采购信息
     * @param wantToBuy
     * @return
     */
    @GetMapping("/downWantToBuyById")
    public R downWantToBuyById(String wantToBuyId){
        WantToBuy wantToBuy = iWantToBuyService.selectWantToBuyById(wantToBuyId);
        if(wantToBuy == null) {
            return R.error("参数错误");
        }
        wantToBuy.setStatus(1);
        iWantToBuyService.updateWantToBuy(wantToBuy);
        return R.ok("下架成功");
    }

    /**
     * 根据采购ID 上架采购信息
     * @param wantToBuy
     * @return
     */
    @GetMapping("/upWantToBuyById")
    public R upWantToBuyById(String wantToBuyId){
        WantToBuy wantToBuy = iWantToBuyService.selectWantToBuyById(wantToBuyId);
        if(wantToBuy == null) {
            return R.error("参数错误");
        }
        wantToBuy.setStatus(0);
        iWantToBuyService.updateWantToBuy(wantToBuy);
        return R.ok("上架成功");
    }

    /**
     * 根据采购ID删除采购信息
     * @param wantToBuy
     * @return
     */
    @GetMapping("/delWantToBuyById")
    public R delWantToBuyById(String wantToBuyId){
        WantToBuy wantToBuy = iWantToBuyService.selectWantToBuyById(wantToBuyId);
        if(wantToBuy == null) {
            return R.error("参数错误");
        }
        iWantToBuyService.deleteWantToBuyById(wantToBuyId);
        return R.ok("删除成功");
    }


    /**
     * 获取求购列表
     * @param pageNum
     * @param pageSize
     * @param wantToBuy+
     * @return
     */
    @GetMapping("/getWantToBuy")
    public R getWantToBuy(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,WantToBuy wantToBuy,String myId){
        // 取消我的求购数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(wantToBuy.getMemberId());
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setWantToBuyNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        // 取消关注求购数字提示
        if (myId != null && !myId.equals("")) {
            JiaqinFollowMember followMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(myId, wantToBuy.getMemberId());
            if (followMember != null) {
                followMember.setWantToBuyNum(0);
                jiaqinFollowMemberService.updateJiaqinFollowMember(followMember);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        PageInfo pageInfo = iWantToBuyService.selectWantToBuyListPageInfo(pageNum,pageSize,wantToBuy);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 根据采购ID获取报价列表
     * @param wantToBuy
     * @return
     */
    @GetMapping("/getQuotedPriceByWantToBuyId")
    public R getQuotedPriceByWantToBuyId(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String wantToBuyId){
        HashMap<String, Object> map = new HashMap<>();
        PageInfo<QuotedPrice> pageInfo = iQuotedPriceService.selectQuotedPriceListByWantToBuyId(pageNum,pageSize,wantToBuyId);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    @Autowired
    private ApiNewController apiNewController;
    @Autowired
    private IWantToBuyService wantToBuyService;
    /**
     * 报价
     * @param quotedPrice
     * @return
     */
    @PostMapping("/quotedPrice")
    public R quotedPrice(@RequestBody QuotedPrice quotedPrice){
        // 防止重复提交
        QuotedPrice qPrice = new QuotedPrice();
        qPrice.setQuotedMemberId(quotedPrice.getQuotedMemberId());
        List<QuotedPrice> quotedPriceList = iQuotedPriceService.selectQuotedPriceList(qPrice);
        for (QuotedPrice qp : quotedPriceList) {
            // 判断是否报过价
            if (qp.getWantToBuyId().equals(quotedPrice.getWantToBuyId())) {
                return R.error("您已报过价，请勿重复报价");
            }
        }
        quotedPrice.setQuotedTime(DateUtils.getNowDate());
        iQuotedPriceService.insertQuotedPrice(quotedPrice);
        // 报价备注添加到留言第一条
        WantToBuy wantToBuyById = wantToBuyService.selectWantToBuyById(quotedPrice.getWantToBuyId());
        if (wantToBuyById != null) {
            MessageUser messageUser = new MessageUser();
            messageUser.setMemberId(quotedPrice.getQuotedMemberId());
            messageUser.setMessageMemberId(wantToBuyById.getMemberId());
            messageUser.setResId(quotedPrice.getWantToBuyId());
            messageUser.setNewMessage(quotedPrice.getRemarks());
            apiNewController.leavingMessage(messageUser);
        }
        return R.ok();
    }

    @Autowired
    private IMemberService memberService;
    @Autowired
    private ISupplyImgService supplyImgService;
    @Autowired
    private IJiaqinFollowMemberService jiaqinFollowMemberService;
    /**
     *  发布供应
     * @return
     */
    @PostMapping("/releaseSupply")
    public R releaseSupply(@RequestBody Supply supply){
        // 不是会员，请先注册会员
        Member memberById = memberService.selectMemberById(supply.getReleaseMember());
        if (memberById == null) {
            return R.error("请先注册");
        }
        if (memberById.getIsVip() == 0 && memberById.getIsJqVip() == 0) {
            return R.error("您不是会员，请先注册会员");
        }
        if (memberById.getStatus() == 1) {
            return R.error("您的账户因违规使用而被冻结，详情请联系我们平台");
        }
        String id = UUID.randomUUID().toString().replace("-", "");
        // 相册图片
        if (supply.getImgUrls() != null) {
            String[] split = supply.getImgUrls().split(",");
            for (String s : split) {
                if (s != null && !s.equals("")) {
                    SupplyImg supplyImg = new SupplyImg();
                    supplyImg.setMemberId(supply.getReleaseMember());
                    supplyImg.setSupplyId(id);
                    supplyImg.setType(0);
                    supplyImg.setPictureUrl(s);
                    supplyImg.setStatus(0);
                    supplyImgService.insertSupplyImg(supplyImg);
                }
            }
        }
        // 拍照图片
        if (supply.getPhotoUrls() != null) {
            String[] split = supply.getPhotoUrls().split(",");
            for (String s : split) {
                if (s != null && !s.equals("")) {
                    SupplyImg supplyImg = new SupplyImg();
                    supplyImg.setMemberId(supply.getReleaseMember());
                    supplyImg.setSupplyId(id);
                    supplyImg.setType(1);
                    supplyImg.setPictureUrl(s);
                    supplyImg.setStatus(0);
                    supplyImgService.insertSupplyImg(supplyImg);
                }
            }
        }

        // 拍照视频
        if (supply.getPhotoVideo() != null) {
            String[] split = supply.getPhotoVideo().split(",");
            for (String s : split) {
                if (s != null && !s.equals("")) {
                    SupplyImg supplyImg = new SupplyImg();
                    supplyImg.setMemberId(supply.getReleaseMember());
                    supplyImg.setSupplyId(id);
                    supplyImg.setType(1);
                    supplyImg.setVideoUrl(s);
                    supplyImg.setStatus(1);
                    supplyImgService.insertSupplyImg(supplyImg);
                }
            }
        }
        // 添加我的供应、关注供应数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(supply.getReleaseMember());

        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setSupplyNum(1);
            numberTipsService.updateNumberTips(tips);
        }
        JiaqinFollowMember followMember = new JiaqinFollowMember();
        followMember.setFollowMemberId(supply.getReleaseMember());
        List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
        if (followMemberList.size() > 0) {
            for (JiaqinFollowMember JFM : followMemberList) {
                JFM.setId(JFM.getId());
                JFM.setSupplyNum(1);
                jiaqinFollowMemberService.updateJiaqinFollowMember(JFM);
                NumberTips byMemberId = numberTipsService.selectNumberTipsByMemberId(JFM.getMemberId());
                if (byMemberId != null) {
                    NumberTips tips1 = new NumberTips();
                    tips1.setId(byMemberId.getId());
                    tips1.setFollowSupplyNum(1);
                    numberTipsService.updateNumberTips(tips1);
                }
            }
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(supply.getDistributionDistance());
        if (supply.getDistributionDistance().equals("")) {
            supply.setDistributionDistance("全国");
        } else if(isNum.matches()){
            supply.setDistributionDistance(supply.getDistributionDistance() + "km");
        }
        supply.setId(id);
        supply.setStatus(0);//设置状态为已上架
        Date date = new Date();
        supply.setReleaseDate(date);//设置发布时间
        supply.setUpdateDate(date);//设置修改时间
        supply.setViews(0L);//设置浏览量=0
        iSupplyService.insertSupply(supply);
        return R.ok("发布供应成功!");
    }

    @Autowired
    private INumberTipsService numberTipsService;
    /**
     *  获取供应列表
     * @return
     */
    @GetMapping("/getSupply")
    public R getSupply(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,Supply supply,String myId,String type){
        // 取消我的供应数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(supply.getReleaseMember());
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setSupplyNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        // 取消关注供应数字提示
        if (myId != null && !myId.equals("")) {
            JiaqinFollowMember followMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(myId, supply.getReleaseMember());
            if (followMember != null) {
                followMember.setSupplyNum(0);
                jiaqinFollowMemberService.updateJiaqinFollowMember(followMember);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        PageInfo<Supply> pageInfo = iSupplyService.getSupply(pageNum,pageSize,supply);
        map.put("data",pageInfo);
        return R.ok(map);
    }


    /**
     * 下架供应
     * @return
     */
    @GetMapping("/downSupply")
    public R downSupply(String supplyId){
        Supply supply = iSupplyService.selectSupplyById(supplyId);
        if(supply == null){
            return R.error("参数错误");
        }
        supply.setStatus(1);
        return  iSupplyService.updateSupply(supply)>0?R.ok("下架成功"):R.error("下架失败");
    }

    /**
     * 上架供应
     *
     * @return
     */
    @GetMapping("/upSupply")
    public R upSupply(String supplyId){
        Supply supply = iSupplyService.selectSupplyById(supplyId);
        if(supply == null){
            return R.error("参数错误");
        }
        supply.setStatus(0);
        return  iSupplyService.updateSupply(supply)>0?R.ok("上架成功"):R.error("上架失败");
    }

    /**
     * 删除供应
     * @param supplyId
     * @return
     */
    @GetMapping("/delSupply")
    public R delSupply(String supplyId){
        Supply supply = iSupplyService.selectSupplyById(supplyId);
        if(supply == null){
            return R.error("参数错误");
        }
        return  iSupplyService.deleteSupplyById(supplyId)>1?R.ok("删除成功"):R.error("删除失败");
    }

    /**
     * 根据供应ID获取供应信息
     * @param supply
     * @return
     */
    @GetMapping("/getSupplyById")
    public R getSupplyById(String supplyId,String userId){
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",iSupplyService.supplyDeatil(supplyId,userId));
        Supply supplyById = iSupplyService.selectSupplyById(supplyId);
        Supply supply = new Supply();
        supply.setId(supplyId);
        supply.setViews(supplyById.getViews() + 1);// 浏览量+1
        iSupplyService.updateSupply(supply);
        return R.ok(map);
    }

    /**
     *  举报供应
     * @return
     */
    @PostMapping("/reportSupply")
    public R reportSupply(@RequestBody ReportSupply reportSupply){
        reportSupply.setReportDate(new Date());
        return iReportSupplyService.insertReportSupply(reportSupply)>0?R.ok("举报成功"):R.error("举报失败");
    }

    /**
     *  举报供应
     * @return
     */
    @PostMapping("/reportQuote")
    public R reportQuoted(@RequestBody ReportQuote reportQuote){
        reportQuote.setReportDate(new Date());
        return iReportQuoteService.insertReportQuote(reportQuote)>0?R.ok("举报成功"):R.error("举报失败");
    }


}
